using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using newsApi.Models;
using newsApi.Services;

namespace newsApi.Controllers;
[EnableCors]
[ApiController]
[Route("api/[controller]")]
public class ChanelController:ControllerBase
{
    private readonly ChanelsService _chanelsService;

    public ChanelController(ChanelsService chanelsService) =>
        _chanelsService=chanelsService;
    //  [Authorize(Role.Admin)]
    [HttpGet]
    public async Task<IActionResult> Get() 
    {
        var result=new List<string>();
        var data=await _chanelsService.GetAsync();
        foreach(var c in data)
        {
            result.Add(c.Title);
        }
        return Ok(result);

    }
    // =>
    //     await _chanelsService.GetAsync();
    // [Authorize(Role.Admin)]
    [HttpPost]
    public async Task<IActionResult> Post(Chanel newChanel)
    {
        await _chanelsService.CreateAsyn(newChanel);
        return CreatedAtAction(nameof(Get), new { id = newChanel.Id }, newChanel);;
    }
    [Authorize]
    // [Authorize(Role.Admin)]
    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<Chanel>> Get(string id)
    {
        var chanel = await _chanelsService.GetAsync(id);

        if (chanel is null)
        {
            return NotFound();
        }

        return chanel;
    }

    [HttpPut("{id:length(24)}")]
    public async Task<IActionResult> Update(string id, Chanel updatedChanel)
    {
        var chanel = await _chanelsService.GetAsync(id);

        if (chanel is null)
        {
            return NotFound();
        }

        updatedChanel.Id = chanel.Id;

        await _chanelsService.UpdateAsync(id, updatedChanel);

        return NoContent();
    }

    [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> Delete(string id)
    {
        var chanel = await _chanelsService.GetAsync(id);

        if (chanel is null)
        {
            return NotFound();
        }

        await _chanelsService.RemoveAsync(id);

        return NoContent();
    }
}